<template>
  <div class="groupNameDetail" id="groupNameDetail">
    <!-- 功能按钮 -->
    <div class="groupNameDetail_button">
      <a-button class="addButton" type="primary" 
      :disabled="!btnPerm.includes('creatAble')"
      @click="addRecord">
        <template #icon>
          <span class="iconfont icon-Add iconadd"></span>
        </template>
        新建
      </a-button>
      <div class="groupSelect">
        所属分组：
        <a-select v-model:value="groupType" @change="groupChange" :options="groupOptions"></a-select>
      </div>
      <div class="statusSelect">
        状态：
        <a-select v-model:value="statusType" @change="statusChange" :options="statusOptions"></a-select>
      </div>
      <div class="searchContent">
        <a-input v-model:value="keyWord" @pressEnter="onSearch" @blur="onSearch" placeholder="搜索用户名、手机号、邮箱号" style="width: 210px">
          <template #suffix>
            <i class="iconfont icon-search" @click="onSearch"></i>
          </template>
        </a-input>
      </div>
    </div>
    <!-- 表格展示部分 -->
    <baseTable :columns="columns.memberManageColumn" :dataSource="configData.records" :isSelect="true" :scroll="scroll"
      ref="hotBaseTables" :isShowPagination="isShowPagination" :showCheckDelete="showCheckDelete"
      :total="configData.total" @deleteRecord="deleteSelectedAll" @changePage="changePage">
      <template #bodyCell="{ column, text, record }">
        <template v-if="column.ellipsis">
          <table-tool-tip :text="text" :column="column"></table-tool-tip>
        </template>
        <template v-if="column.dataIndex === 'isEnabled'">
          <a-switch @click="switchChange(record)" size="small" :disabled="isPrevent" v-model:checked="record.isEnabled" />
        </template>
        <template v-if="column.dataIndex === 'oparation'">
          <a class="eidtRecords" :class="{ disable: !btnPerm.includes('detailAble') }" @click="showDetail(record)">{{ record.oparation[0] }}</a>
          <a class="eidtRecords1" @click="resetPassWord(record)">重置密码</a>
          <a class="eidtRecords1" :class="{ disable: !btnPerm.includes('editAble') }" @click="editRecord(record)">{{
            record.oparation[1]
          }}</a>
          <a-popconfirm placement="topRight" 
          :disabled="!btnPerm.includes('deleteAble')"
          @confirm="confirmDelete(record)">
            <template #title>
              <p style="width: 197px">
                是否删除该会员
              </p>
            </template>
            <a :class="{ disable: !btnPerm.includes('deleteAble') }">{{ record.oparation[2] }}</a>
          </a-popconfirm>
        </template>
      </template>
      <template #otherOpration>
        <a-button :style="{ 'margin-left': '8px' }" :disabled="!rowSelection.length"
          @click="handleEnable('enable')">启用</a-button>
        <a-button :style="{ 'margin-left': '8px' }" :disabled="!rowSelection.length"
          @click="handleEnable('disable')">禁用</a-button>
        <a-button :style="{ 'margin-left': '8px' }" @click="deleteSelectedAll"
          :disabled="!rowSelection.length || !btnPerm.includes('deleteAble')">删除</a-button>
      </template>
    </baseTable>

    <!-- 会员详情-->
    <base-modal :width="modAlProps.width" :isVisible="isVisible" :title="modAlProps.title" :cancleText="cancleText"
      :buttons="buttons" @handleOk="buttonMessage" @handleCancle="(isVisible = false)" class="sensitive_modal"
      v-if="isVisible">
      <template v-slot:body>
        <a-form name="advanced_search" autoComplete="off" :model="memberFormState" ref="member_REF">
          <template v-for="(item, index) in memberFormState">
            <div class="basic-item" v-if="item.componentName !== 'password'|| isAdd">
              <component :is="comps[item.componentName]" :formNamePath="[index, 'value']" :index="index" :element="item"
                v-if="item" />
            </div>

          </template>
        </a-form>
      </template>
    </base-modal>
     <!-- 重置密码-->
     <base-modal :width="'M'" :isVisible="isVisibleReset" :title="modAlProps.title" :cancleText="cancleText"
      :buttons="buttons2" @handleOk="buttonMessageReset" @handleCancle="cancleReset" class="sensitive_modal"
      v-if="isVisibleReset">
      <template v-slot:body>
        <a-form
        :model="formState"
          name="advanced_search"
          class="ant-advanced-search-form"
          autoComplete="off"
          ref="userManageFrom"
        >
          <a-form-item class="user-input" :label="formState.resetPwd.label" :name="['resetPwd','value']"
          :rules="formState.resetPwd.rule">
            <a-input-password style="width: 508px;" v-model:value="formState.resetPwd.value" placeholder="请输入"
              allow-clear/>
          </a-form-item>
          <a-form-item class="user-input" :label="formState.repetPwd.label" :name="['repetPwd','value']"
          :rules="formState.repetPwd.rule">
            <a-input-password style="width: 508px;" v-model:value="formState.repetPwd.value" placeholder="请输入"
              allow-clear/>
          </a-form-item>
        </a-form>
      </template>
    </base-modal>
  </div>
</template>
<script lang="ts" setup>
import { ref, reactive, computed, onMounted, watch, nextTick, createVNode } from "vue";
import baseTable from "@/components/table/baseTable.vue";
import tableToolTip from "@/components/table/tableToolTip.vue";
import { useRoute } from "vue-router";
import columns from "@/components/table/tableConfig/columnsName";
import { getTableScroll } from "@/components/table/tableConfig/table";
import msgModal from "@/components/modal/modelConfig/MsGModal";
import upload from "@/components/upload/uploadFile.vue";
import baseForm from "@/components/form/baseForm.vue";
import { comps } from '@/components/draggable/exportComp'
import baseModal from "@/components/modal/baseModal.vue";
import { Modal, message } from "ant-design-vue";
import type { DrawerProps } from "ant-design-vue";
import request from "@/api/index";
import { cloneDeep } from "lodash";
import { scrollType, modeProp } from "@/type.d";
import { encrypt3DES, decrypt3DES } from "@/utils/cryptojs";
import {routerPerm} from '@/utils/common';
// type
type configDataType = {
  total: number;
  size: number;
  records: any[];
};
interface dataSourceType {
  [propName: string]: any;
}
interface FormState {
  password: string;
  remember: boolean;
}
//专门验证用户名是否重复！
const checkCreatSiteForm = async (
  _rule: dataSourceType = {},
  value: any
) => {
  if (!value) {
    return Promise.reject(`${_rule.msg1}`);
  } else {
    var params = Object.assign({
      name: value,
    })
    if (detailData.id) {
      params.id = detailData.id
    }
    if (_rule.api) {
      let res = await request[`${_rule.api}`](params);
      if (!res) {
        return Promise.reject(`${_rule.msg2}`);
      } else {
        return Promise.resolve();
      }
    }
  }
};

const checkRepetPwd = ( _rule: dataSourceType = {},value: any) => {
  if (!value) {
    return Promise.reject(`${_rule.msg1}`);
  } else {
    if (value !== formState.resetPwd.value) {
      return Promise.reject(`${_rule.msg2}`);
    }else {
      return Promise.resolve();
    }
  }
};

//data
const formState = reactive<dataSourceType>({
  resetPwd: {
    value: "",
    rule: {
      required: true,
      trigger: ["blur"],
      message: "重置密码不能为空！",
    },
    id: "",
    label: "重置密码",
  },
  repetPwd: {
    value: "",
    rule: {
      required: true,
      trigger: ["blur"],
      validator: checkRepetPwd,
      msg1: "确认密码不能为空！",
      msg2: "两次密码不一致！",
    },
    id: "",
    label: "确认密码",
  },
});
const manageId = ref<any>(null);
const isVisibleReset = ref<Boolean>(false);
const btnPerm = ref<any[]>([]);
const memberFormState = ref<dataSourceType[]>([]);
const memberFormState_origin = ref<any>('');
const instanceItems = ref<dataSourceType[]>([]);
let detailData = reactive<dataSourceType>({});
const statusOptions = [{ value: "全部" }, { value: "禁用" }, { value: "启用" }];
const groupOptions = ref<dataSourceType[]>([{ value: "全部" }]);
const statusType = ref<string | number>("全部");
const groupType = ref<string | number>("全部");
const groupValue = ref<string | number>("");
const cancleText = ref<string>("");
const isPrevent = ref<boolean>(false);
const statusValue = ref<string | number>("");
const { query } = useRoute();
let scroll: scrollType = reactive({ y: "", isFixed: false }); // 表单滚动设置
const isShowPagination = true; // 是否需要配分页器
const showCheckDelete = true; // 是否需要分页器中的自定义全选和删除
const configId = ref<number>(0);
//表格数据
let configData = reactive<configDataType>({ total: 0, size: 10, records: [] });
const hotBaseTables = ref<any>(null);
const addNewTables = ref<any>(null);
let rowSelection = ref<(string | number)[]>([]);
let moveRowSelection = ref<(string | number)[]>([]);
const deleteArr = ref<(string | number)[]>([]);
const memberModelId = ref<number | null>(null);
// 模态框数据
const isAdd = ref<boolean>(true); //判断是新家、编辑或者批量上传来复用模态框
const isVisible = ref<boolean>(false);
const keyWord = ref<string>("");
let datas = reactive<dataSourceType>({})
let modAlProps: modeProp = reactive({
  width: "L",
  title: "新建会员",
});
const member_REF = ref();
const userManageFrom = ref();
// 分页
const pageCurrent = ref(0);
const pageSize = ref(10);

//methods
const onSearch = async () => {
  //搜索获取数据参数配置
  datas.keyWord = keyWord.value;
  getRecord();
};

const switchChange = (record: any) => {
  let params: dataSourceType = {
    ids: [record.id],
  };
  request[!record.isEnabled ? 'fetchMemberDisable' : 'fetchMemberEnable'](params)
    .then((res: any) => {
      if (res.code == "00000 00000") {
        message.success(res.message);
        getRecord();
      } else {
        message.error(res.message);
      }
    })
    .catch((err: any) => {
      throw new Error(err);
    });
};

const statusChange = () => {
  //模型范围
  statusValue.value =
    statusType.value === "启用" ? "1" : statusType.value === "禁用" ? "0" : "";
  getRecord();
};
const groupChange = (value: any, data: any) => {
  //所属分组
  groupValue.value = data.id;
  getRecord();
};


const buttons = ref<dataSourceType[]>([]); //模态框button按钮个数和文案修改
const buttons2 = ref<dataSourceType[]>([
    {
      text: "确认",
      "html-type": "submit",
      keepAlive: true,
    },
  ]);
// computed
rowSelection = computed(() => {
  return hotBaseTables.value.selectedRowKeys;
});

moveRowSelection = computed(() => {
  return addNewTables.value.selectedRowKeys;
});

//methods
const resetData = () => {
  memberFormState.value = [];
  nextTick(() => {
    memberFormState.value = JSON.parse(memberFormState_origin.value);
    memberFormState.value.length && memberFormState.value.forEach((item: dataSourceType) => {

      if (isPrevent.value && item.param === 'memberStatus') {
        item.disabled = true
      } else {
        item.disabled = false
      }
      if (item.componentName == 'userName') {
        item.rule.validator = checkCreatSiteForm;
      } else {
        if (item.rule.validator) {
          item.rule.validator = new Function(
            "return " + item.rule.validator
          )();
        }
      }
      console.log(item.value, 9390123)
    });
  })



}
const addRecord = async () => {
  //添加会员数据
  isVisible.value = true;
  isAdd.value = true;
  modAlProps.title = "新建会员";
  modAlProps.width = "L";
  resetData();
  detailData.id = '';

  cancleText.value = '取消'
  buttons.value = [
    {
      text: "保存",
      "html-type": "submit",
      keepAlive: true,
    },
    {
      text: "保存并继续新建",
      "html-type": "submit",
      keepAlive: true,
    },
  ];
};

const resetPassWord = (record: any) => {
  console.log(record,'重置密码！');
  modAlProps.title = "重置密码";
  manageId.value = record.id;
  isVisibleReset.value = true;
};

const editRecord = async (record: any) => {
  if(!btnPerm.value.includes('editAble')) return
  detailData = await request.fetchMemberDetail({ id: record.id });
  memberFormState.value.length && memberFormState.value.forEach((item: dataSourceType) => {
    detailData.instance?.instanceItems && detailData.instance.instanceItems.length && detailData.instance.instanceItems.forEach((dItem: dataSourceType) => {

      if (item.param === 'password' && item.param === dItem.field) {
        item.value = decrypt3DES(dItem.value)
      } else if (item.param === dItem.field && item.param !== 'password') {
        item.value = dItem.value
      }
      if (isPrevent.value && item.param === 'memberStatus') {
        item.disabled = true
      } else {
        item.disabled = false
      }
    })
  })
  //编辑会员数据
  isVisible.value = true;
  isAdd.value = false;
  modAlProps.title = "编辑会员";
  modAlProps.width = "L";
  cancleText.value = '取消'
  buttons.value = [
    {
      text: "保存",
      "html-type": "submit",
      keepAlive: true,
    },
  ];
};

const showDetail = async (record: dataSourceType) => {
  if(!btnPerm.value.includes('detailAble')) return
  //编辑会员数据
  detailData = await request.fetchMemberDetail({ id: record.id });
  memberFormState.value.length && memberFormState.value.forEach((item: dataSourceType) => {
    detailData.instance?.instanceItems && detailData.instance.instanceItems.length && detailData.instance.instanceItems.forEach((dItem: dataSourceType) => {
      if (item.param === 'password' && item.param === dItem.field) {
        item.value = decrypt3DES(dItem.value)
      } else if (item.param === dItem.field && item.param !== 'password') {
        item.value = dItem.value
      }
      item.disabled = true
    })
  })
  cancleText.value = '关闭'
  isAdd.value = true;
  isVisible.value = true;
  modAlProps.title = "会员详情";
  buttons.value = [
    // {
    //   text: "保存",
    //   "html-type": "submit",
    //   keepAlive: true,
    // },
  ];
};

const cancleReset = () => {
  userManageFrom.value.resetFields();
  isVisibleReset.value = false;
};
// 重置密码
const buttonMessageReset = () => {
  userManageFrom.value.validate()
    .then(() => {
      const params = {
        id: manageId.value,
        password: encrypt3DES(formState.resetPwd.value),
        repeatePassword: encrypt3DES(formState.repetPwd.value)
      }
      request.fetchUserResetpwd(params).then((res: any) => {
        if (res.code == "00000 00000") {
          userManageFrom.value.resetFields()
          getRecord();
          isVisibleReset.value = false;
          message.success(res.message);
        } else {
          message.error(res.message);
        }
      }).catch((err: any) => {
        throw new Error(err);
      });
    })
};

// 新添或编辑会员分组调取接口
const buttonMessage = async (msg: dataSourceType) => {
  let params1: dataSourceType = {
    instanceItems: instanceItems.value,
    modelId: memberModelId.value
  };
  let params2: dataSourceType = {}
  if (!isAdd.value) {
    params2 = {
      id: detailData.id,
      instance: {
        instanceItems: instanceItems.value,
        modelId: detailData.instance.modelId
      }
    }
  };
  member_REF.value.validate()
    .then(() => {
      request[isAdd.value ? 'fetchMemberAddNew' : 'fetchMemberUpdate'](isAdd.value ? params1 : params2).then((res: any) => {
        if (res.code == "00000 00000") {
          resetData();
          getRecord();

          message.success(res.message);
        } else {
          message.error(res.message);
        }
      }).catch((err: any) => {
        throw new Error(err);
      });
      isVisible.value = msg.text == "保存" ? false : true;
      isAdd.value = false;
    })
};

// 删除单个会员
const confirmDelete = async (item: any) => {
  deleteArr.value = [item.id];
  deleteRecords(deleteArr.value);
};


const handleEnable = (type: string) => {
  let params: dataSourceType = {
    ids: rowSelection.value,
  };
  request[type === 'disable' ? 'fetchMemberDisable' : 'fetchMemberEnable'](params)
    .then((res: any) => {
      if (res.code == "00000 00000") {
        message.success(res.message);
        getRecord();
      } else {
        message.error(res.message);
      }
    })
    .catch((err: any) => {
      throw new Error(err);
    });

}

//删除已选所有会员
const deleteSelectedAll = async () => {
  let keys = rowSelection.value;
  Modal.confirm(
    Object.assign({}, msgModal.confirm, {
      title: "是否将所选的会员删除？",
      content:
        "",
      icon: createVNode("i", {
        class: "iconfont icon-warn warning_ICON",

      }),
      okText: "确定",
      onOk: async () => {
        await deleteRecords(keys);
        Modal.destroyAll();
      },
      onCancel() {
        Modal.destroyAll();
      },
    })
  );
};

const deleteRecords = async (keys: (string | number)[] = []) => {
  // 调接口删除会员
  await request.fetchMemberDelete({ ids: keys }).then((res: any) => {
    if (res.code == "00000 00000") {
      message.success(res.message);
      getRecord();
    } else {
      message.error(res.message);
    }
  });
};

// 检测是否开启密级管理
const isOpenPrevent = async () => {
  isPrevent.value = await request.isOpenPrevent();
}

const getRecord = async () => {
  // 获取会员表格数据
  const data: {} = {
    pageNumber: pageCurrent.value,
    pageSize: pageSize.value,
    pageSort: "",
    groupId: groupValue.value || '',
    keyWord: datas.keyWord || "",
    status: statusValue.value || "",
  };
  const groupData = (await request.fetchMemberPage(data)) || {};
  let reqData = groupData;
  let sourceData = reactive({});
  const records: any[] = [];
  reqData?.records?.map((item: any, index: number) => {
    sourceData = {
      createTime: item.createTime,
      groupId: item.groupId,
      groupName: item.groupName,
      isEnabled: item.isEnabled,
      lastLoginTime: item.lastLoginTime,
      nickName: item.nickName,
      userName: item.userName,
      userPhone: item.userPhone,
      userEmail: item.userEmail,
      id: item.id,
      oparation: ["详情", "编辑", "删除"],
    };
    records.push(sourceData);
  });
  configData.total = reqData.total;
  configData.size = reqData.size;
  configData.records = records;
  hotBaseTables.value.selectedRowKeys = [];
  nextTick(() => {
    scroll.y = getTableScroll(74, "groupNameDetail").y;
    scroll.isFixed = getTableScroll(74, "groupNameDetail").isFixed;
  });
};

//切换分页器
const changePage = (data: { pageCurrent: any; pageSize: any }) => {
  pageCurrent.value = data.pageCurrent;
  pageSize.value = data.pageSize;
  getRecord();
};

const getGroup = async () => {
  let options = await request.fetchMemberGroupList();
  groupOptions.value = [{ name: "全部", id: null }, ...options]
  groupOptions.value.map((item: any) => (item.value = item.name));
};

//获取详情
const getDetail = async () => {
  const data = await request.fetchModelMemberModel()
  memberModelId.value = data.id
  memberFormState.value = JSON.parse(data.enableJson);
  memberFormState.value.forEach((item: dataSourceType) => {
    if (item.componentName == 'userName') {
      item.rule.validator = checkCreatSiteForm;
    } else {
      if (item.rule.validator) {
        item.rule.validator = new Function(
          "return " + item.rule.validator
        )();
      }
    }
  });
  memberFormState_origin.value = data.enableJson;// 存一份原始的数据供新建的时候使用

}

//watch
watch(() => memberFormState.value, (newVal, oldVal) => {
  instanceItems.value = []
  newVal.length && newVal.forEach((item: dataSourceType) => {
    let obj: dataSourceType = {}
    if (item.param === 'password') {
      obj.field = item.param;
      obj.value = encrypt3DES(item.value)
    } else {
      obj.field = item.param;
      obj.value = item.value || '';
    }
    instanceItems.value.push(obj)
  })
}, { deep: true })

//onmounted
onMounted(() => {
  btnPerm.value = routerPerm()
  isOpenPrevent()
  getRecord();
  getDetail();
  getGroup();
});
</script>
<style lang="scss" scoped>
.groupNameDetail {
  width: 100%;
  height: calc(100% - 72px);
  padding: 16px;
  background-color: #fff;

  .groupNameDetail_button {
    padding-bottom: 24px;
    display: flex;

    .addButton {
      display: flex;
      align-items: center;
      margin-right: 8px;

      .iconadd {
        font-size: 24px;
        margin-right: 4px;
      }
    }

    .importButton {
      font-weight: 400;
      color: rgba(0, 0, 0, 0.85);
      margin-right: 8px;
    }

    .groupSelect {
      margin-left: auto;
    }

    .statusSelect {
      margin-left: 16px;
    }

    .searchContent {
      margin-right: 0px;
      margin-left: 16px;

      .icon-search {
        font-size: 20px;
        color: rgba(0, 0, 0, 0.45);
        position: absolute;
        right: 12px;
        top: 0px;
      }
    }
  }

  :deep(.ant-table-cell:nth-last-of-type(1)) {
    text-align: right;
    margin-right: 16px;
  }

  .eidtRecords {
    margin-right: 16px;
  }

  .eidtRecords1 {
    margin-right: 16px;
  }
}
.disable {
  color: rgba(0, 0, 0, 0.25);
  cursor: not-allowed;
}
.add-item {
  .header-content {
    display: flex;
    flex-direction: row;
    align-items: center;
    margin-bottom: 24px;

    ::v-deep(.group-select .ant-select) {
      width: 288px;
    }

    .searchContent {
      margin-left: 16px;
      width: 192px;
      height: 32px;

      ::v-deep(.ant-input-affix-wrapper) {
        height: 32px;
      }
    }
  }
}

.move-item {
  display: flex;
  flex-direction: column;

  span {
    margin-bottom: 8px;
  }
}

:deep(.ant-form-item) {
  width: 604px;
  display: flex;

  .ant-form-item-control {
    width: 508px;
    margin-left: 4px;
    flex: unset;
  }

  .ant-form-item-label {
    flex-grow: 0;
    width: 80px;
    text-align: right;
  }
}

::v-deep(.groupSelect .ant-select) {
  width: 112px;
}

::v-deep(.statusSelect .ant-select) {
  width: 112px;
}

::v-deep(.move-item .ant-select) {
  width: 492px;
}

::v-deep(.ant-form-item-control-input-content:hover) {
  .anticon-close-circle {
    display: block;
  }

  .ant-input-show-count-suffix {
    // display: none;
  }
}
</style>
